package com.flow.framework.core.system.initialization;

import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.common.util.verify.VerifyUtil;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Function;

/**
 * 验证器辅助类
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/23
 */
@Slf4j
public class ValidationHelper {

    private static Validator validator = null;

    static void setValidator(Validator systemValidator) {
        validator = systemValidator;
    }

    /**
     * 根据spring注解校验对象
     *
     * @param pojo     需要校验的对象
     * @param callback 校验不通过时的回调（参数为错误信息）
     * @param groups   需要校验的分组
     * @param <T>      T
     */
    public static <T> void validateByOpenSourceAnnotation(T pojo, Function<List<String>, CheckedException> callback, Class<?>... groups) {
        final Set<ConstraintViolation<T>> violationSet = validator.validate(pojo, groups);
        if (VerifyUtil.isEmpty(violationSet)) {
            return;
        }
        List<String> messages = new ArrayList<>();
        for (ConstraintViolation violation : violationSet) {
            String message = violation.getMessage();
            if (VerifyUtil.isEmpty(message)) {
                continue;
            }
            messages.add(message);
        }
        log.error("validate pojo result: {}", String.join(";", messages));
        throw callback.apply(messages);
    }

    /**
     * 根据框架注解校验对象，校验未通过则直接抛异常
     *
     * @param pojo   需要校验的对象
     * @param groups 需要校验的分组
     * @param <T>    T
     */
    public static <T> void validateByFrameworkAnnotation(T pojo, Class<?>... groups) {
        validator.validate(pojo, groups);
    }
}
